import 'dart:typed_data';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'aes_cryptor.dart';

class FileHelper {
  final AESCryptor _cryptor = AESCryptor();

  // Save file to a specified directory
  static Future<void> saveToDirectory(
      File file, String directoryPath, String fileName) async {
    final directory = Directory(directoryPath);
    if (!await directory.exists()) {
      await directory.create(recursive: true);
    }
    final newPath = '${directory.path}/$fileName';
    await file.copy(newPath);
  }

  static Future<File> getTempFile(File selectedFile) async {
    final tempDir = await getTemporaryDirectory();
    final tempPath = tempDir.path;
    final originalFileName = selectedFile.path.split('/').last;
    final tempFile = File('$tempPath/$originalFileName');
    return tempFile;
  }

  Future<File> fileEncrypt(File selectedFile, String password) async {
    Uint8List fileBytes = await selectedFile.readAsBytes();
    Uint8List encryptedBytes = _cryptor.encrypt(fileBytes, password);
    File tempFile = await getTempFile(selectedFile);
    await tempFile.writeAsBytes(encryptedBytes);
    return tempFile;
  }

  Future<File> fileDecrypt(File selectedFile, String password) async {
    Uint8List fileBytes = await selectedFile.readAsBytes();
    Uint8List decryptedBytes = _cryptor.decrypt(fileBytes, password);
    File tempFile = await getTempFile(selectedFile);
    await tempFile.writeAsBytes(decryptedBytes);
    return tempFile;
  }
}
